package com.nineclock.common.filter;

import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")//拦截所有的路径
public class CurrentUserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        try {
//            //获取上下文对象
//            SecurityContext context = SecurityContextHolder.getContext();
//            //获取认证信息
//            Authentication authentication = context.getAuthentication();
//            String name = authentication.getName();
//            if ( name != null && ! name.equals("anonymousUser")){
//                System.out.println(name);
//                //把json串转换为UserInfo类型
//                UserInfo userInfo = JsonUtils.toBean(name, UserInfo.class);
//                //存储到当前线程
//                CurrentUserHolder.set(userInfo);
//            }
            chain.doFilter(request,response);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (ServletException e) {
//            e.printStackTrace();
//        } finally {
//            CurrentUserHolder.remove();
//        }
    }
}
